package org.zero.db;

import lombok.SneakyThrows;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.util.Properties;

/**
 * DBCP增强类
 * 依赖 Apache Commons DBCP2
 *
 * @author Zero
 */
public class Dbcp2Enhancer {
    private final Properties properties = new Properties();
    private DataSource dataSource;

    public Dbcp2Enhancer() {
    }

    public Dbcp2Enhancer(String fileName) {
        createDataSourceFromClassPath(fileName);
    }

    @SneakyThrows
    public DataSource createDataSourceFromFilePath(String filePath) {
        InputStream inputStream = Files.newInputStream(Paths.get(filePath));
        return createDataSourceFromInputStream(inputStream);
    }

    public DataSource createDataSourceFromClassPath(String fileName) {
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName);
        return createDataSourceFromInputStream(inputStream);
    }

    @SneakyThrows
    public DataSource createDataSourceFromInputStream(InputStream inputStream) {
        properties.load(inputStream);
        return createDataSourceFromProperties();
    }

    @SneakyThrows
    public DataSource createDataSourceFromProperties() {
        dataSource = BasicDataSourceFactory.createDataSource(properties);
        return dataSource;
    }

    public DataSource getDataSource() {
        if (dataSource == null) {
            createDataSourceFromProperties();
        }

        return dataSource;
    }

    @SneakyThrows
    public Connection getConnection() {
        return getDataSource().getConnection();
    }
}
